import os
import subprocess
import sys

from utils.config_manager import NetworkConfigManager
from utils.log_util import get_logger


class IpSwitcher:
    """IP切换功能类，封装网络配置操作"""

    def __init__(self, adapter_name="以太网"):
        self.adapter_name = adapter_name
        self.config_manager = NetworkConfigManager()
        self.logger = get_logger()

    def _run_netsh_command(self, command):
        """执行netsh命令并返回结果"""
        try:
            result = subprocess.run(
                command,
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )
            return result.stdout.strip()
        except subprocess.CalledProcessError as e:
            self.logger.error(f"命令执行失败: {e.stderr}")
            raise RuntimeError(f"网络配置失败: {e.stderr}")

    def switch_to(self, network_type="internal"):
        """通过子进程调用提权程序"""
        try:
            base_path = getattr(
                sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))
            )

            if getattr(sys, "frozen", False):
                base_dir = os.path.dirname(sys.executable)
                switcher_path = os.path.join(base_dir, "switch_network.exe")
                self.logger.info(f"switcher_path:{switcher_path}")
                # 添加UAC触发机制
                if os.name == "nt":
                    params = f'"{switcher_path}" {network_type}'
                    cmd = f'powershell Start-Process -FilePath "{switcher_path}" -ArgumentList "{network_type}" -Verb RunAs'
                    result = subprocess.run(
                        cmd, shell=True, capture_output=True, text=True, timeout=60
                    )
                else:
                    result = subprocess.run(
                        [switcher_path, network_type],
                        capture_output=True,
                        text=True,
                        timeout=30,
                    )
            else:
                python_exe = sys.executable
                script_path = os.path.join(
                    os.path.dirname(__file__), "..", "switch_network.py"
                )
                self.logger.info(f"script_path:{script_path}")
                result = subprocess.run(
                    [python_exe, script_path, network_type],
                    capture_output=True,
                    text=True,
                    timeout=30,
                )

            if result.returncode != 0:
                self.logger.error(f"网络切换失败: {result}")
                return False

            return True
        except Exception as e:
            self.logger.error(f"网络切换异常: {str(e)}")
            return False

    def _set_dhcp(self):
        """设置DHCP配置"""
        self.logger.info("开始设置DHCP配置...")

        # 设置DHCP获取IP地址
        cmd_ip = (
            f'netsh interface ip set address name="{self.adapter_name}" source=dhcp'
        )
        self._run_netsh_command(cmd_ip)
        self.logger.info("IP地址设置为DHCP获取")

        # 设置DHCP获取DNS
        cmd_dns = (
            f'netsh interface ip set dnsservers name="{self.adapter_name}" source=dhcp'
        )
        self._run_netsh_command(cmd_dns)
        self.logger.info("DNS设置为DHCP获取")
        return True

    def _set_static(self, config):
        """设置静态IP配置"""
        ip = config.get("ip", "")
        mask = config.get("mask", "")
        gateway = config.get("gateway", "")
        dns1 = config.get("dns1", "")
        dns2 = config.get("dns2", "")

        if not ip or not mask:
            self.logger.info("静态IP配置不完整")
            return False

        self.logger.info(f"开始设置静态IP: {ip}/{mask}...")
        self.logger.info(f"网关: {gateway} DNS: {dns1}, {dns2}")

        # 设置静态IP
        cmd_ip = (
            f'netsh interface ip set address name="{self.adapter_name}" '
            f"static {ip} {mask} {gateway} 1"
        )
        self._run_netsh_command(cmd_ip)
        self.logger.info("IP地址设置成功")

        # 设置DNS服务器
        success_dns = True

        if dns1:
            cmd_dns1 = f'netsh interface ip set dnsservers name="{self.adapter_name}" static {dns1} primary'
            if self._run_netsh_command(cmd_dns1) is None:
                success_dns = False

        if dns2:
            cmd_dns2 = f'netsh interface ip add dnsservers name="{self.adapter_name}" {dns2} index=2'
            if self._run_netsh_command(cmd_dns2) is None:
                success_dns = False

        self.logger.info("DNS设置成功" if success_dns else "DNS设置失败")
        return True

    def get_current_config(self):
        """获取当前网络配置"""
        self.logger.info("获取当前网络配置...")
        cmd = "ipconfig /all"
        result = self._run_netsh_command(cmd)
        return result if result else "无法获取网络配置"
